package com.zj;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @program: concurrent
 * @description:
 * @author: zy
 * @create: 2022-01-20 09:49
 */
public class DownLoadTask implements Runnable {
    private Logger logger= Logger.getLogger(   DownLoadTask.class);
    //第几个线程
    private final int i;
    //文件总大小
    private final long fileSize;
    //启动的线程总数
    private final int threadSize;
    //每个线程要下载的文件大小
    private final long sizePerThread;
    //要下载的文件url地址
    private final String url;
    //文件在本地的地址
    private final String newFileAddress;

    private Notify notify;



    public DownLoadTask(int i, long fileSize, int threadSize, long sizePerThread, String url, String newFileAddress, Notify notify) {
        this.i = i;
        this.fileSize = fileSize;
        this.threadSize = threadSize;
        this.sizePerThread = sizePerThread;
        this.url = url;
        this.newFileAddress = newFileAddress;

        this.notify=notify;
    }

    @Override
    public void run() {
        //计算起始位置
        long start=i*sizePerThread;   //  +已经下载的量。
        long end=(i+1)*sizePerThread-1;   // 0: 0-20      1:21-41    2: 42-62
        RandomAccessFile raf=null;
        InputStream iis=null;
        try {
             raf = new RandomAccessFile(newFileAddress, "rw");
            //关键，指定起始位置
            raf.seek(start);

            //TODO: 开始下载
            URL urlobj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(10 * 1000);
            con.setRequestProperty("Range", "bytes=" + start + "-" + end);

            //要用到输入流
             iis = new BufferedInputStream(con.getInputStream());
            byte[] bs = new byte[1024*1024];
            int length = -1;
            while ((length = iis.read(bs, 0, bs.length)) != -1) {
                raf.write(bs, 0, length);
                //System.out.println("**********" + length);
                if(   this.notify!=null){
                    this.notify.notifyResult(   length );
                }
            }
            logger.info( "线程"+i+"下载完毕.");
        }catch(InterruptedIOException ex1){
            //写入文件   输出流
            //   .tmp临时文件存每个线程下载的文件的位置         类来存信息
            //          将以上的信息 int i, long fileSize, int threadSize, long sizePerThread, String url, String newFileAddress
            //              多加个一个  当前线程的下载量   downloadedSize
            //                  ObjectOutputStrem 写入到  。ｔｍｐ文件中　．　
        }catch( Exception ex){

            ex.printStackTrace();
            logger.error(   ex.getMessage());
        }finally{
            if( raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if( iis!=null){
                try {
                    iis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
